package com.party.jackclientandroid.base;

import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.services.core.PoiItem;
import com.party.jackclientandroid.BaseActivity;
import com.party.jackclientandroid.BaseFragment;
import com.party.jackclientandroid.R;
import com.party.jackclientandroid.adapter.FilterAdapter;
import com.party.jackclientandroid.api.DefaultConsumer;
import com.party.jackclientandroid.api.SearchService;
import com.party.jackclientandroid.bean.BaseResult;
import com.party.jackclientandroid.bean.FilterCondition;
import com.party.jackclientandroid.bean.OrderCondition;
import com.party.jackclientandroid.loadviewhelper.load.LoadViewHelper;
import com.party.jackclientandroid.ui_home.activity.SearchActivity;
import com.party.jackclientandroid.ui_mine.choose_location.ChooseLocationActivity;
import com.party.jackclientandroid.utils.ConstUtils;
import com.party.jackclientandroid.view.OrderFilterView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 搜索筛选界面的公用代码。
 */

public abstract class BaseFragmentFilter extends BaseFragment {
    @BindView(R.id.drawer_layout)
    public DrawerLayout mDrawerLayout;
    @BindView(R.id.right_menu)
    public RecyclerView mFilterRecyclerView;
    @BindView(R.id.tv_search_key)
    public TextView tv_search_key;
    @BindView(R.id.title_tv)
    public TextView title_tv;
    @BindView(R.id.filter_icon)
    public ImageView filterIcon;
    @BindView(R.id.tv_show_filter_layout)
    public TextView filterBtn;
    @BindView(R.id.refresh_layout)
    public SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.recycler_view)
    public RecyclerView mRecyclerView;
    @BindView(R.id.ll_container)
    public ViewGroup ll_container;
    @BindView(R.id.tv_delete_search_content)
    public ImageView tv_delete_search_content;
    @BindView(R.id.location_tv)
    public TextView location_tv;
    @BindView(R.id.btn_back)
    public View btn_back;
    List<OrderCondition> titleList = new ArrayList<>();
    List<FilterCondition> filterConditionList = new ArrayList<>();
    // 选中的类型
    private List<FilterCondition> searchCondition = new ArrayList<>();
    FilterAdapter mFilterAdapter;
    public SearchService searchService;
    public String categoryId;
    public String conditionType;
    public String needSearchKey = "";
    /**
     * 评分价格
     */
    public JSONObject leftJsonObject;
    /**
     * 右边的筛选
     */
    public JSONObject rightJsonObject;
    public JSONArray jsonArray;
    public String jsonDataStr;
    public List<OrderFilterView> orderByViewList = new ArrayList<>();
    public double longitude;
    public double latitude;
    public String areaId, areaName;


    /**
     * 显示筛选界面
     *
     * @param view
     */
    @OnClick(R.id.tv_show_filter_layout)
    public void showFilterLayout(View view) {
        mDrawerLayout.openDrawer(Gravity.RIGHT);
    }

    public void showFilter() {
        if (filterConditionList.size() == 0) {
            loadingFilterData();
        }
    }

    @Override
    protected void initData() {
        getDefaultLocation();
        helper = new LoadViewHelper(mRefreshLayout);
    }

    public void getNeedData() {
        helper.showLoading();
        tv_search_key.setText(needSearchKey);
        location_tv.setText(areaName);
        changeFilterBtn(searchCondition);
        tv_delete_search_content.setVisibility((needSearchKey != null && needSearchKey.length() > 0) ? View.VISIBLE : View.GONE);
    }

    public void finishData(List datas) {
        if (datas.size() == 0) {
            helper.showEmpty();
        } else {
            helper.showContent();
        }
    }

    public void getDefaultLocation() {
        longitude = mApplication.getMap().getLongitude();
        latitude = mApplication.getMap().getLatitude();
        areaId = mApplication.getMap().getAdCode();
        areaName = mApplication.getMap().getStreet();
        categoryId = getActivity().getIntent().getStringExtra("categoryId");
        conditionType = getActivity().getIntent().getStringExtra("conditionType");
        needSearchKey = getActivity().getIntent().getStringExtra("needSearchKey");
    }

    /**
     * 清空删除
     */
    @OnClick(R.id.tv_delete_search_content)
    public void deleteSearchContent() {
        needSearchKey = null;
        tv_search_key.setHint("请输入搜索内容");
        mRefreshLayout.autoRefresh();
    }


    public void hideFilterLayout() {
        mDrawerLayout.closeDrawer(Gravity.RIGHT);
    }

    public boolean isDrawerOpen() {
        return mDrawerLayout.isDrawerOpen(Gravity.RIGHT);
    }

    private DrawerLayout.SimpleDrawerListener mSimpleDrawerListener = new DrawerLayout.SimpleDrawerListener() {
        @Override
        public void onDrawerOpened(View drawerView) {
            //档DrawerLayout打开时，让整体DrawerLayout布局可以响应点击事件
            showFilter();
            drawerView.setClickable(true);
        }

        @Override
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
        }
    };


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) return;
        switch (requestCode) {
            case ConstUtils.SEARCH_LOCATION_CODE:
                PoiItem poiItem = data.getParcelableExtra(ConstUtils.SEARCH_LOCATION_CODE + "");
                if (poiItem == null) return;
                latitude = poiItem.getLatLonPoint().getLatitude();
                longitude = poiItem.getLatLonPoint().getLongitude();
                areaId = poiItem.getAdCode();
                areaName = poiItem.getTitle();
                mRefreshLayout.autoRefresh();
                break;
            case ConstUtils.SEARCH_KEY:
                needSearchKey = data.getStringExtra(ConstUtils.SEARCH_KEY + "");
                mRefreshLayout.autoRefresh();
                break;
        }
    }


    /**
     * 初始化 筛选界面
     */
    public void initFilterLayout() {
        searchService = new SearchService((BaseActivity) mActivity);
        mFilterAdapter = new FilterAdapter(mActivity, filterConditionList, searchCondition);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(mActivity, 3);
        mFilterRecyclerView.setAdapter(mFilterAdapter);
        mFilterRecyclerView.setLayoutManager(gridLayoutManager);
        mFilterAdapter.setItemListener((View v) -> {
            searchCondition.clear();
            int position = (int) v.getTag();
            FilterCondition filterCondition = filterConditionList.get(position);
            searchCondition.add(filterCondition);
            mFilterAdapter.notifyDataSetChanged();
        });
        getShopCategoryList();
        mDrawerLayout.addDrawerListener(mSimpleDrawerListener);
        loadingFilterData();
    }

    public void onClickTabItem(int position) {
        for (int i = 0; i < orderByViewList.size(); i++) {
            OrderFilterView orderFilterView = orderByViewList.get(i);
            if (position != i){
                orderFilterView.clean();
            }else {
                orderFilterView.select();
                leftJsonObject = orderFilterView.getSearchKey();
            }
        }
        searchConditionCommitWork();
    }


    @BindView(R.id.tab_1)
    OrderFilterView tabLayout1;
    @BindView(R.id.tab_2)
    OrderFilterView tabLayout2;
    @BindView(R.id.tab_3)
    OrderFilterView tabLayout3;

    public void getShopCategoryList() {
        addDisposableIoMain(searchService.getOrderByCondition("0", conditionType), new DefaultConsumer<List<OrderCondition>>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<List<OrderCondition>> baseBean) {
                titleList = baseBean.getData();
                OrderFilterView tabLayout = null;
                for (int i = 0; i < titleList.size(); i++) {
                    switch (i) {
                        case 0:
                            tabLayout = tabLayout1;
                            break;
                        case 1:
                            tabLayout = tabLayout2;
                            break;
                        case 2:
                            tabLayout = tabLayout3;
                            break;
                    }
                    tabLayout.setTag(i);
                    tabLayout.setVisibility(View.VISIBLE);
                    tabLayout.setOnClickListener((View v) -> {
                        int index = (int) v.getTag();
                        onClickTabItem(index);
                    });
                    orderByViewList.add(tabLayout);
                    tabLayout.setData(titleList.get(i));
                }
            }
        });
    }


    public void loadingFilterData() {
        addDisposableIoMain(searchService.getFilterCondition(), new DefaultConsumer<List<FilterCondition>>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<List<FilterCondition>> baseBean) {
                title_tv.setText(baseBean.getData().get(0).getTitle());
                filterConditionList.addAll(baseBean.getData().get(0).getData());
                initDefaultCategory(filterConditionList);
                changeFilterBtn(searchCondition);
                mFilterAdapter.notifyDataSetChanged();
            }
        });
    }

    /**
     * 设置默认的选择类型。
     *
     * @param data
     */
    private void initDefaultCategory(List<FilterCondition> data) {
        if (categoryId != null && categoryId.trim().length() > 0) {
            int id = Integer.parseInt(categoryId);
            for (int i = 0; i < data.size(); i++) {
                if (id == (data.get(i).getId())) {
                    searchCondition.add(data.get(i));
                    return;
                }
            }
        }
    }

    /**
     * 改变筛选按钮颜色
     */
    public void changeFilterBtn(List<FilterCondition> data) {
        if (data.size() > 0) {
            filterIcon.setImageResource(R.mipmap.filter1);
            filterBtn.setTextColor(getResources().getColor(R.color.colorMain));
        } else {
            filterIcon.setImageResource(R.mipmap.filter);
            filterBtn.setTextColor(getResources().getColor(R.color.black));
        }
    }

    @OnClick(R.id.filter_reset)
    public void resetData(View view) {
        searchCondition.clear();
        mFilterAdapter.notifyDataSetChanged();
        mDrawerLayout.closeDrawer(Gravity.RIGHT);
        searchConditionCommitWork();
    }

    @OnClick(R.id.filter_commit)
    public void dataCommit(View view) {
        mFilterAdapter.notifyDataSetChanged();
        mDrawerLayout.closeDrawer(Gravity.RIGHT);
        searchConditionCommitWork();
    }

    private void searchConditionCommitWork() {
        jsonArray = new JSONArray();
        if (leftJsonObject != null) {
            jsonArray.put(leftJsonObject);
        }
        if (searchCondition.size() > 0) {
            rightJsonObject = new JSONObject();
            FilterCondition filterCondition = searchCondition.get(0);
            try {
                rightJsonObject.put("key", filterCondition.getKey());
                rightJsonObject.put("type", filterCondition.getType());
                rightJsonObject.put("value", filterCondition.getValue());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            jsonArray.put(rightJsonObject);
        }
        jsonDataStr = jsonArray.length() > 0 ? jsonArray.toString() : null;
        mRefreshLayout.autoRefresh();
    }


    @OnClick({R.id.locate_ll, R.id.search_ll})
    public void handleClickSth(View view) {
        switch (view.getId()) {
            case R.id.locate_ll:
                Intent intent = new Intent(getActivity(), ChooseLocationActivity.class);
                startActivityForResult(intent, ConstUtils.SEARCH_LOCATION_CODE);
                break;
            case R.id.search_ll:
                Intent intent1 = new Intent(mActivity, SearchActivity.class);
                startActivityForResult(intent1, ConstUtils.SEARCH_KEY);
                break;
        }
    }
}
